package com.oracle.zebrafreelytraveling.ui.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import com.oracle.zebrafreelytraveling.App;
import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.bean.User;
import com.oracle.zebrafreelytraveling.db.DBManager;
import com.oracle.zebrafreelytraveling.utils.ImageUtil;
import com.oracle.zebrafreelytraveling.utils.UserUtil;

import java.io.File;
import java.io.IOException;

import static android.app.Activity.RESULT_OK;

/**
 * Created by yydcnjjw on 2017/7/30.
 */

public class GetImgDialogFragment extends DialogFragment implements View.OnClickListener {

    public static final String GET_IMG_DIALOG_FRAGMENT = "GetImgDialogFragment";

    private View mView;

    private TextView mTvPickImg;
    private TextView mTvCaptureImg;

    private Context mContext = App.getContextObject();

    public static final int REQUEST_IMAGE_PICK = 100;
    public static final int REQUEST_IMAGE_CAPTURE = 101;

    private Uri currentImagePath;

    private OnCurrentPathListener listener;

    public static GetImgDialogFragment newInstance(){
        GetImgDialogFragment f = new GetImgDialogFragment();
        return f;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        mView = inflater.inflate(R.layout.fragment_get_img_dialog, container);
        initView();
        requestPermission();
        return mView;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (listener == null) {
            listener = (OnCurrentPathListener) context;
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (listener == null) {
            listener = (OnCurrentPathListener) activity;
        }
    }

    public void showDialogFragment(FragmentManager fragmentManager){
        show(fragmentManager, GET_IMG_DIALOG_FRAGMENT);
    }

    private void initView() {
        mTvCaptureImg = (TextView) mView.findViewById(R.id.capture_photo);
        mTvPickImg = (TextView) mView.findViewById(R.id.pick_photo);

        mTvPickImg.setOnClickListener(this);
        mTvCaptureImg.setOnClickListener(this);
    }

    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.CAMERA)) {
                //解释应用需要的权限
            } else {
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.CAMERA},
                        REQUEST_IMAGE_PICK);
            }
        } else if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                //解释应用需要的权限
            } else {
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_IMAGE_CAPTURE);
            }
        }
    }

    /**
     * 本地获取图片
     */
    private void pickPhoto() {
        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Intent captureintent = new Intent(Intent.ACTION_GET_CONTENT);
            captureintent.setType("image/*");
            startActivityForResult(captureintent, REQUEST_IMAGE_PICK);
        }
    }

    /**
     * 拍照获取图片
     */
    private void capturePhoto() throws Exception {
        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Intent takePictureIntent = new Intent("android.media.action.IMAGE_CAPTURE");
            if (takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) {
                File photoFile = createImageFile();
                Uri photoURI = null;
                if (Build.VERSION.SDK_INT < 24) {
                    photoURI = Uri.fromFile(photoFile);
                } else {
                    photoURI = FileProvider
                            .getUriForFile(getActivity(), "com.oracle.zebrafreelytraveling.fileprovider", photoFile);
                }
                currentImagePath = photoURI;
                Log.d("currentImagePath", currentImagePath + "");
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

    //image/user/img_十三位时间戳_userId.jpg;
    private File createImageFile() throws Exception {
        User user = UserUtil.getUserInfoFromSP();
        String imgFileName = "img_" + System.currentTimeMillis() + "_" + user.getUserId() + ".jpg";
        File outputImage = new File(getActivity().getExternalCacheDir(), imgFileName);
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputImage;
    }

    private void handlePickPhoto(Intent data) throws Exception {
        String imagePath = null;
        if (Build.VERSION.SDK_INT >= 19) {
            // 4.4及以上系统使用这个方法处理图片
            imagePath = ImageUtil.handleImageOnKitKat(data);
            listener.getPath(Uri.fromFile(new File(imagePath)));
        } else {
            // 4.4以下系统使用这个方法处理图片
            imagePath = ImageUtil.handleImageBeforeKitKat(data);
            listener.getPath(Uri.fromFile(new File(imagePath)));
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_IMAGE_CAPTURE:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        Uri uri = data.getData();
                        if (uri != null){
                            listener.getPath(uri);
                        } else {
                            listener.getPath(currentImagePath);
                        }
                    } else {
                        listener.getPath(currentImagePath);
                    }
                }
                break;
            case REQUEST_IMAGE_PICK:
                if (resultCode == RESULT_OK) {
                    try {
                        handlePickPhoto(data);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
        dismissAllowingStateLoss();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.capture_photo:
                try {
                    capturePhoto();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.pick_photo:
                pickPhoto();
                break;
        }
    }

    public interface OnCurrentPathListener {
        void getPath(Uri currentPath);
    }

}
